/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package sudoku;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.plaf.ColorUIResource;
/**
 *
 * @author user3
 */
public class Square extends JButton implements ActionListener{

	private int num;
	private boolean[] cans;

	private void openMenu() {
		JPopupMenu menu = new JPopupMenu();
		for(int i = 0; i <= length; i++) {
			JCheckBoxMenuItem item = new JCheckBoxMenuItem();
			if(i == num) {
				item.setState(true);
			}
			item.setActionCommand(new String() + i);
			item.addActionListener(this);
			item.setText((i != 0) ? new String() + i : new String());
			menu.add(item);
			if(i == 0) {
				menu.addSeparator();
			}
		}
		menu.show(this, DIM / 2, DIM / 2);
	}

	private void set(int n) {
		num = n;
		if(n == 0) {
			setBackground(Color.BLUE);
			setText(new String());
		} else {
			setText(new String() + n);
		}
		for(int i = 0; i < length; i++) {
			cans[i] = true;
		}
	}

	public final int length;

	public static final int DIM = 60;

	public Square(int len) {
		num = 0;
		cans = new boolean [len];
		length = len;
		for(int i = 0; i < length; i++) {
			cans[i] = true;
		}
		setBackground(Color.BLUE);
		setFont(new Font("Courier new", 0, 26));

		setActionCommand("menu");
		addActionListener(this);
	}

	@Override
	public Dimension getMinimumSize() {
		return new Dimension(DIM, DIM);
	}

	@Override
	public Dimension getPreferredSize() {
		return new Dimension(DIM, DIM);
	}

	@Override
	public Dimension getMaximumSize() {
		return new Dimension(DIM, DIM);
	}

	//true - if the square changed in the method
	public void is(int n) {
		if(cans[n - 1]) {
			set(n);
		}
		else {
			this.setBackground(Color.RED);
			throw new RuntimeException("worng");
		}
	}

	//true - if the square changed in the method
	public void cant(int n) {
		if(!cans[n - 1]) {
			throw new RuntimeException("worng");
		}
		cans[n - 1] = false;
		
		int count = 0;
		int m = 0;
		for(int i = 0; i < cans.length; i++) {
			if(cans[i]) {
				m = i + 1;
				count++;
			}
		}
		if(count == 1) {
			set(m);
		}
	}

	public boolean can(int n) {
		return (num == 0) ? cans[n - 1] : num == n;
	}

	public int get() {
		return num;
	}

	public void actionPerformed(ActionEvent e) {
		String command = e.getActionCommand();
		if(command.equals("menu")) {
			openMenu();
		}
		else {
			int n = Integer.parseInt(command);
			setBackground(ColorUIResource.GREEN);
			set(n);
		}
	}
}
